#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include "RingQueue.hpp"
#include "Task.hpp"

const char *option = "+-*/%";

void *Productor(void *args)
{
  Ringqueue<Task> *rq = static_cast<Ringqueue<Task> *>(args);
  // sleep(3);
  while (true)
  {
    int data1 = rand() % 10;
    usleep(10);
    int data2 = rand() % 10;
    char op = option[rand() % strlen(option)];

    Task t(data1, data2, op);
    printf("productor get a task: %s\n", t.getTask().c_str());
    rq->push(t);
    // std::cout << "生产一个任务: " << data << std::endl;

    sleep(1);
  }

  // std::cout << "Productor thread......" << std::endl;
  // sleep(1);
}

void *Consumer(void *args)
{
  Ringqueue<Task> *rq = static_cast<Ringqueue<Task> *>(args);
  // sleep(3);
  while (true)
  {
    Task t;
    rq->pop(&t);
    // std::cout << "消费一个任务: " << data << std::endl;
    printf("consumer get a task: %s, result: %s\n", t.getTask().c_str(), t.getResult().c_str());
    // sleep(1);
    // std::cout << "Consumer thread......" << std::endl;
    // sleep(1);
  }
}

int main()
{
  // 创建一个环形队列
  // Ringqueue<int> *rq = new Ringqueue<int>();
  Ringqueue<Task> *rq = new Ringqueue<Task>();

  // 创建线程
  pthread_t c[5], p[3];
  for (int i = 0; i < 3; i++)
  {
    pthread_create(p + i, nullptr, Productor, rq);
  }

  for (int i = 0; i < 5; i++)
  {
    pthread_create(c + i, nullptr, Consumer, rq);
  }

  // 线程等待
  for (int i = 0; i < 5; i++)
  {
    pthread_join(c[i], nullptr);
  }

  for (int i = 0; i < 3; i++)
  {
    pthread_join(p[i], nullptr);
  }

  return 0;
}